package com.educate.book.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.book.dao.ChildBookDao;
import com.educate.book.model.bo.ChildBookBO;
import com.educate.book.model.po.ChildBook;
import com.educate.book.rpc.api.ChildBookService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class ChildBookServiceImpl implements ChildBookService {

    @Resource ChildBookDao childBookDao;

    @Override
    public void create(ChildBookBO bo) {
        childBookDao.insert(bo);
    }

    @Override
    public void delete(ChildBookBO bo) {
        childBookDao.delete(bo);
    }

    @Override
    public void delete(String childBookId) {
        childBookDao.deleteById(childBookId);
    }

    @Override
    public ChildBookBO detail(String childBookId) {
        Optional<ChildBook> optional = childBookDao.findById(childBookId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new ChildBookBO(optional.get());
    }

    @Override
    public ChildBookBO detail(ChildBookBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(ChildBookBO bo) {
        Optional<ChildBook> optional = childBookDao.findById(bo.getChildBookId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        childBookDao.save(optional.get());
    }

    @Override
    public Page<ChildBookBO> query(ChildBookBO bo, PageRequest pageRequest) {
        return childBookDao.query(bo, pageRequest).map(ChildBookBO::new);
    }

    @Override
    public List<ChildBookBO> list(ChildBookBO bo) {
        List<ChildBook> result = childBookDao.findAll();
        return ListUtils.map(result, ChildBookBO::new);
    }
}
